package com.example.wenzh.myapplication;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    private ImageView img;
    private Button button;
    private int[] imgs = {R.drawable.a2018,R.drawable.b2018,R.drawable.c2018,R.drawable.d2018};
    private int index = 0;
    private Handler handler;
    private final int CHANGE_DOG = 1001;
    private boolean isPause = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = findViewById(R.id.img);
        button = findViewById(R.id.button);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what == CHANGE_DOG){
                    index = (index+1)%imgs.length;
                    img.setImageResource(imgs[index]);
                    return true;
                }
                return false;
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try{
                        Thread.sleep(2000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    if (!isPause){
                        Message message = new Message();
                        message.what = CHANGE_DOG;
                        handler.sendMessage(message);
                    }
                }
            }
        }).start();

        //打完new 后按shif+ctrl+空格
        //选中onclicklistener按alt+enter
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                isPause = !isPause;
            }




        });
    }
}
